#!/bin/sh

#LEDs solid on initialize start
echo 1 > /sys/class/leds/mt76-phy0/brightness;
echo 1 > /sys/class/leds/zbt-we826\:green\:wifi/brightness;

#loop forever until we get a response from the gateway
while true 
do
	#check each time in case the cable wasn't connected when we booted ....
	gateway_ip="$(ip ro | grep default | cut -d' ' -f3)";

	ping -c 1 $gateway_ip
	rc=$?
	if [[ $rc -eq 0 ]] ; then
		uci set fm.node.gateway_ip="$gateway_ip";
		break;
	else
		sleep 1;
	fi
done

mac="$(/sbin/ifconfig eth0 | head -1 | awk '{print $5}')";
ap_info="$(wget -O - http://$gateway_ip/cgi-bin/handler.cgi?m=$mac)";
#FreeMesh2GHz || 9876543210 || FreeMesh || 9876543210 || <backbone ssid> || <backbone key> || <next static>
echo "$(date) - ap_info: $ap_info" >> /tmp/init.log;

#todo - add a check here for if we get something valid back?
ap_two_ssid="$(echo $ap_info | cut -d',' -f1)";
echo "$(date) - $ap_two_ssid" >> /tmp/init.log;
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?l=$ap_two_ssid;
ap_two_key="$(echo $ap_info | cut -d',' -f2)";
echo "$(date) - $ap_two_key" >> /tmp/init.log;
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?l=$ap_two_key;
ap_five_ssid="$(echo $ap_info | cut -d',' -f3)";
echo "$(date) - $ap_five_ssid" >> /tmp/init.log;
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?l=$ap_five_ssid;
ap_five_key="$(echo $ap_info | cut -d',' -f4)";
echo "$(date) - $ap_five_key" >> /tmp/init.log;
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?l=$ap_five_key;
mesh_five_ssid="$(echo $ap_info | cut -d',' -f5)";
echo "$(date) - $mesh_five_ssid" >> /tmp/init.log;
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?l=$mesh_five_ssid;
mesh_five_key="$(echo $ap_info | cut -d',' -f6)";
echo "$(date) - $mesh_five_key" >> /tmp/init.log;
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?l=$mesh_five_key;
static="$(echo $ap_info | cut -d',' -f7)";
echo "$(date) - static: $static" >> /tmp/init.log;
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?l=$static;

uci set wireless.ap_two.ssid="$ap_two_ssid";
uci set wireless.ap_two.key="$ap_two_key";
uci set wireless.ap_five.ssid="$ap_five_ssid";
uci set wireless.ap_five.key="$ap_five_key";
uci set wireless.mesh_five.mesh_id="$mesh_five_ssid";
uci set wireless.mesh_five.key="$mesh_five_key";

uci set network.lan.ipaddr="$static";

uci set dhcp.lan.ignore='1';

uci commit;
echo "$(date) - committed all the changes to uci" >> /tmp/init.log;

# Tell router to increment next_static
int="$(echo $static | cut -d'.' -f4)";
wget -O - http://$gateway_ip/cgi-bin/handler.cgi?i=$int;
echo "$(date) - called the router to let it know to increment" >> /tmp/init.log;

#flash leds on initialize end
/freemesh/flashled.sh 0 &
echo "$(date) - started flashing LEDs" >> /tmp/init.log;

#change the node pw to the mesh backchannel wifi key
/freemesh/change_pw.sh &
echo "$(date) - changed the pw" >> /tmp/init.log;

